package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.constant.CacheConstants;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.IdUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.customer.CustomerInfoAccountToken;
import com.probox.common.entity.mapper.customer.CustomerInfoAccountTokenMapper;
import com.probox.common.entity.service.customer.ICustomerInfoAccountService;
import com.probox.common.entity.service.customer.ICustomerInfoAccountTokenService;
import com.probox.customer.api.domain.CustomerInfoAccount;
import com.probox.systemApi.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 客户信息TOKENService业务层处理
 *
 * @author zhusiyu
 * @date 2021-05-25
 */
@Service
@Transactional
public class CustomerInfoAccountTokenServiceImpl extends ServiceImpl<CustomerInfoAccountTokenMapper, CustomerInfoAccountToken> implements ICustomerInfoAccountTokenService
{
    @Autowired
    private CustomerInfoAccountTokenMapper customerInfoAccountTokenMapper;

    @Autowired
    private ICustomerInfoAccountService customerInfoAccountService;

    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> sops;

    /**
     * 查询客户信息TOKEN
     *
     * @param tokenId 客户信息TOKENID
     * @return 客户信息TOKEN
     */
    @Override
    public CustomerInfoAccountToken selectCustomerInfoAccountTokenById(Long tokenId)
    {
        return this.getById(tokenId);
    }

    /**
     * 查询客户信息TOKEN列表
     *
     * @param customerInfoAccountToken 客户信息TOKEN
     * @return 客户信息TOKEN
     */
    @Override
    public List<CustomerInfoAccountToken> queryList(CustomerInfoAccountToken customerInfoAccountToken)
    {
        QueryWrapper<CustomerInfoAccountToken> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(customerInfoAccountToken.getTokenId()))&&customerInfoAccountToken.getTokenId()!=null)
        {
            queryWrapper.eq("TOKEN_ID", customerInfoAccountToken.getTokenId());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerInfoAccountToken.getCustomerUid()))&&customerInfoAccountToken.getCustomerUid()!=null)
        {
            queryWrapper.eq("CUSTOMER_UID", customerInfoAccountToken.getCustomerUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerInfoAccountToken.getCustomerAccountUid()))&&customerInfoAccountToken.getCustomerAccountUid()!=null)
        {
            queryWrapper.eq("CUSTOMER_ACCOUNT_UID", customerInfoAccountToken.getCustomerAccountUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerInfoAccountToken.getAccessToken()))&&customerInfoAccountToken.getAccessToken()!=null)
        {
            queryWrapper.eq("ACCESS_TOKEN", customerInfoAccountToken.getAccessToken());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerInfoAccountToken.getSecretKey()))&&customerInfoAccountToken.getSecretKey()!=null)
        {
            queryWrapper.eq("SECRET_KEY", customerInfoAccountToken.getSecretKey());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerInfoAccountToken.getDataStatus()))&&customerInfoAccountToken.getDataStatus()!=null)
        {
            queryWrapper.eq("DATA_STATUS", customerInfoAccountToken.getDataStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerInfoAccountToken.getExpireTime()))&&customerInfoAccountToken.getExpireTime()!=null)
        {
            queryWrapper.eq("EXPIRE_TIME", customerInfoAccountToken.getExpireTime());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerInfoAccountToken.getCreateUser()))&&customerInfoAccountToken.getCreateUser()!=null)
        {
            queryWrapper.eq("CREATE_USER", customerInfoAccountToken.getCreateUser());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerInfoAccountToken.getOpenId()))&&customerInfoAccountToken.getOpenId()!=null)
        {
            queryWrapper.eq("OPEN_ID", customerInfoAccountToken.getOpenId());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerInfoAccountToken.getPlatformUid()))&&customerInfoAccountToken.getPlatformUid()!=null)
        {
            queryWrapper.eq("PLATFORM_UID", customerInfoAccountToken.getPlatformUid());
        }
        return customerInfoAccountTokenMapper.selectList(queryWrapper);
    }

    /**
     * 新增客户信息TOKEN
     *
     * @param customerInfoAccountToken 客户信息TOKEN
     * @return 结果
     */
    @Override
    public boolean insertCustomerInfoAccountToken(CustomerInfoAccountToken customerInfoAccountToken)
    {

        return this.save(customerInfoAccountToken);

    }

    /**
     * 修改客户信息TOKEN
     *
     * @param customerInfoAccountToken 客户信息TOKEN
     * @return 结果
     */
    @Override
    public boolean updateCustomerInfoAccountToken(CustomerInfoAccountToken customerInfoAccountToken)
    {

        return this.updateById(customerInfoAccountToken);
    }

    /**
     * 批量删除客户信息TOKEN
     *
     * @param tokenIds 需要删除的客户信息TOKENID
     * @return 结果
     */
    @Override
    public boolean deleteCustomerInfoAccountTokenByIds(Long[] tokenIds)
    {
        return this.removeByIds(Arrays.asList(tokenIds));
    }

    @Override
    public Boolean addCustomerToken(LoginUser loginUser) {
        //添加token表数据
        CustomerInfoAccountToken customerInfoAccountToken = new CustomerInfoAccountToken();
        customerInfoAccountToken.setCustomerUid(loginUser.getUserid());
        customerInfoAccountToken.setCustomerAccountUid(loginUser.getAccountUid());
        customerInfoAccountToken.setAccessToken(loginUser.getToken());
        customerInfoAccountToken.setClientIp(loginUser.getIpaddr());
        customerInfoAccountToken.setCreateTime(DateUtil.date());
        customerInfoAccountToken.setDataStatus("1");
//        customerInfoAccountToken.setCreateUser(SecurityUtils.getUserId());
//        Long platformId = SecurityUtils.getPlatformId();
//        customerInfoAccountToken.setPlatformUid(platformId);

        return this.save(customerInfoAccountToken);
    }

    //token的过期时间
    private static final Long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;
    @Override
    public CustomerInfoAccountToken createAccountInfoToken(CustomerInfoAccount accountInfo) {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String CustomerToken = req.getHeader("CustomerToken");
        String loginToken = sops.get(CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER + CustomerToken);
        CustomerInfoAccountToken token  = new CustomerInfoAccountToken();
        if(StringUtils.isEmpty(loginToken)){
            token.setAccessToken(IdUtils.fastUUID());
            token.setClientIp(SecurityUtils.getCustomerClientIp());
            token.setCreateName(accountInfo.getAccountName());
            token.setCreateTime(new Date());
            token.setCreateUser(accountInfo.getCustomerUid());
            token.setUpdateName(token.getCreateName());
            token.setCustomerUid(accountInfo.getCustomerUid());
            token.setOpenId(accountInfo.getOpenId());
            token.setCustomerAccountUid(accountInfo.getCustomerAccountUid());
            token.setDataStatus("1");
            token.setSourcePort(SecurityUtils.getCustomerSourcePort());
            token.setExpireTime(DateUtils.add(EXPIRE_TIME));
            token.setPlatformUid(accountInfo.getPlatformUid());
            token.setSecretKey(SecurityUtils.getCustomerSecretKey());
            if (this.save(token)) {
                String key = CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER+token.getAccessToken();
                sops.set(key, JSON.toJSONString(token),EXPIRE_TIME, TimeUnit.MINUTES);
                return token;
            }
        }else {
            QueryWrapper<CustomerInfoAccountToken> accountTokenQueryWrapper = new QueryWrapper<>();
            accountTokenQueryWrapper.eq("ACCESS_TOKEN",CustomerToken);
            token = customerInfoAccountTokenMapper.selectOne(accountTokenQueryWrapper);
            token.setCustomerUid(accountInfo.getCustomerUid());
            customerInfoAccountTokenMapper.updateById(token);
            String key = CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER+token.getAccessToken();
            sops.set(key, JSON.toJSONString(token),EXPIRE_TIME, TimeUnit.MINUTES);
            return token;
        }
        return null;
    }


}
